package com.mmd.manage.web;

import com.mmd.bean.CODE;
import com.mmd.bean.WebJsonBean;
import com.mmd.common.entity.MmdImg;
import com.mmd.exception.GameException;
import com.mmd.manage.service.FileService;
import com.mmd.utils.RandomUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * @Author cyq
 * @Date 2019/8/24 12:28
 * @Description
 **/
@RequestMapping(value = "/api/file")
@Controller
public class FileController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    FileService fileService;

    @RequestMapping(value = "/upload")
    @ResponseBody
    public WebJsonBean upload(HttpServletRequest request, HttpServletResponse response,
                              @RequestParam MultipartFile[] files) throws IOException {
        for (int i = 0; i < files.length; i++) {
            if (files[i].isEmpty()) {
                throw new GameException(CODE.FAIL);
            }
            long fileSize = files[i].getSize();
            logger.info("size:" + fileSize);
            if (5 * 1024 * 1024 < fileSize) {
                throw new GameException(new CODE(9999, String.format("文件超过限制，单个图片最大%sKB！", 5 * 1024)));
            }
        }
        String imgId = RandomUtil.generateString(15);
        for (int i = 0; i < files.length; i++) {
            String originalFilename = files[i].getOriginalFilename();
            int index = originalFilename.lastIndexOf(".");
            String suffixStr = originalFilename.substring(index + 1);
            logger.info("originalFilename:" + originalFilename);
            // 存储图片

            MmdImg img = new MmdImg();
            img.setImgId(imgId);
            img.setName(originalFilename);
            img.setCreateTime(new Date());
            img.setImgSuffixStr(suffixStr);
            img.setImg(files[i].getBytes());
            fileService.upload(img);
        }
        return new WebJsonBean(CODE.SUCCESS, imgId);
    }

    @RequestMapping(value = "/show")
    public void show(String imgId,HttpServletRequest request, HttpServletResponse response) throws IOException {
        MmdImg img = fileService.getImg(imgId);
//        response.setContentType("application/octet-stream");
        String agent = request.getHeader("User-Agent");
        boolean isMSIE = (agent != null && agent.contains("MSIE"));
        String fileName = img.getName();
        if (isMSIE) {
            fileName = java.net.URLEncoder.encode(fileName, "UTF8");
        } else {
            //兼容火狐，否则中文乱码
            fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        }
        response.addHeader("Content-Disposition", "attachment; filename="+fileName);
        response.getOutputStream().write(img.getImg());
    }

    @RequestMapping(value = "/upload2")
    @ResponseBody
    public WebJsonBean upload2(HttpServletRequest request, HttpServletResponse response,
                              @RequestParam MultipartFile[] files) throws IOException {
        for (int i = 0; i < files.length; i++) {
            if (files[i].isEmpty()) {
                throw new GameException(CODE.FAIL);
            }
            long fileSize = files[i].getSize();
            logger.info("size:" + fileSize);
            if (5 * 1024 * 1024 < fileSize) {
                throw new GameException(new CODE(9999, String.format("文件超过限制，单个图片最大%sKB！", 5 * 1024)));
            }
        }
        String imgId = RandomUtil.generateString(15);
        for (int i = 0; i < files.length; i++) {
            String originalFilename = files[i].getOriginalFilename();
            int index = originalFilename.lastIndexOf(".");
            String suffixStr = originalFilename.substring(index + 1);
            logger.info("originalFilename:" + originalFilename);
            // 存储图片

            MmdImg img = new MmdImg();
            img.setImgId(imgId);
            img.setName(originalFilename);
            img.setCreateTime(new Date());
            img.setImgSuffixStr(suffixStr);
            img.setImg(files[i].getBytes());
            fileService.upload(img);
        }
        return new WebJsonBean(CODE.SUCCESS, "http://mmd-sit.tscyq.com/mmd-manage/api/file/show?imgId="+imgId);
    }

}
